<!-- 
 * 招投标管理 - 管理员用
 * @author: 张锋
 * @since: 2025-02-10
 * index.vue
-->
<template>
  <div class="Projects-management-container h100">
    <div class="listPage">
      <div class="search">
        <!-- <Filters :formModel="state.formModel" :formLabel="state.formLabel" @reset="reset" @filter="filter"></Filters> -->
      </div>
      <div class="table">
        <!-- 管理招投标项目列表 -->
        <TableCom v-if="state.isSupplier == -1" :tableHeader="state.tableHeader" :tableData="state.tableData" :btnData="state.btnData"
          @getCurrentChange="getCurrentChange" @comEvent="tableEventCom" @colSelect="colSelect"
          @refresh="getAllProjects()" :pagination="state.pagination" :loading="loading"
          @getSelectChange="getSelectChange" @getSizeChange="getSizeChange" handleWidth="250">
          <functionBtn  :btnList="btnList" @clickHandle="clickHandle"></functionBtn>
        </TableCom>
        <!-- 供应商投标项目列表 -->
        <TableCom v-if="state.isSupplier > -1"  :tableHeader="state.tableHeader" :tableData="state.tableData" :timeStamp="state.timeStamp" :btnData="state.btnData1"
          @getCurrentChange="getCurrentChange" @comEvent="tableEventCom" @colSelect="colSelect"
          @refresh="getAllProjects()" :pagination="state.pagination" :loading="loading"
          @getSelectChange="getSelectChange" @getSizeChange="getSizeChange" handleWidth="250">
        </TableCom>
      </div>
    </div>

    <TenderingDrawer v-if="state.isSupplier == -1" :isShowDrawer="isShowProjectsDrawer" @close="ProjectsDrawerClose" :ProjectsId="state.ProjectsId"
      @refresh="getAllProjects()" :data="state.ProjectsRowData"></TenderingDrawer>

    <toubiaoDrawer v-if="state.isSupplier > -1" :isShowDrawer="isShowProjectsDrawer" @close="ProjectsDrawerClose" :id="state.id" :ProjectsId="state.ProjectsId"
    @refresh="getAllProjects()" :isEditToubiao="state.isEditToubiao" :data="state.ProjectsRowData"></toubiaoDrawer>
    
    <projectsMemberSetting v-if="isShowProjectsMember" :isShowDrawer="isShowProjectsMember" @close="ProjectsMemberClose"
      :data="state.ProjectsRowData" @refresh="getAllProjects()"></projectsMemberSetting>


    <el-dialog v-model="state.dialogVisible" width="60%">
      <!-- 123 -->
      <el-table :data="state.toubiaoDetailTable" border>
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="createUserName" label="供应商" align="center" />
        <el-table-column prop="totalPrice" label="总价（元）" align="center" />
        <el-table-column prop="taxPrice" label="税金（元）" align="center" />
        <el-table-column prop="includTaxPrice" label="含税价格（元）" align="center" />
        <el-table-column prop="untaxedPrice" label="未税价格（元）" align="center" />
        <el-table-column prop="fileArray" label="文件" align="center" >
          <template #default="scope">
            <a :href="scope.row.fileArray">投标附件</a>
        </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive, onMounted, ref, inject, onActivated } from 'vue'
import { sessionstorage } from "@/utils/storage";
import {
  getAllProjectsListAPI,
  delProjects,
  // batchdelRole,
  batchStartRole,
  batchStopRole,
  getToubiaoInfo
} from '@/api/interface/Tendering.js'
import { successHandle, colFilters } from '@/utils/common.js'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
const router = useRouter()
const store = useStore()
const state = reactive({
  dialogVisible: false,
  timeStamp: 0,
  toubiaoDetailTable: [],
  id: '',
  formModel: {
    //搜索列表的参数
    projectName: '', //项目名称
    valid: '', //状态
  },
  formLabel: [
    {
      label: '项目名称',
      model: 'projectName',
      type: 'text',
      width: '160',
      placeholder: '请输入项目名称',
    },
    {
      label: '状态',
      model: 'projectStatus',
      type: 'select',
      width: '160',
      option: [
        {
          key: '全部',
          value: '',
        },
        {
          key: '启用',
          value: true,
        },
        {
          key: '禁用',
          value: false,
        },
      ],
    },
  ],
  tableData: [],
  tableHeader: [
    {
      label: '项目名称',
      prop: 'projectName',
    },
    {
      label: '项目描述',
      prop: 'projectRemark',
    },
    {
      label: '开标时间',
      prop: 'startDate',
    },
  ],
  btnData: [
    {
      name: '编辑项目',
      icon: 'bianji',
      color: '#25D390',
      change: 'edit',
    },
    {
      name: '删除',
      icon: 'shanchu',
      color: '#F74B33',
      change: 'del',
    },
    {
      name: '查看投标',
      icon: 'shanchu',
      color: '#25D390',
      change: 'detail',
    },
  ],

  btnData1: [
    {
      name: '投标',
      icon: 'bianji',
      color: '#25D390',
      change: 'toubiao',
    },
    {
      name: '修改',
      icon: 'bianji',
      color: '#25D390',
      change: 'edittoubiao',
    },
  ],
  ProjectsId: null, //项目id
  pagination: {
    //分页
    currentPage: 1,
    size: 10,
    total: 0,
  },
  ProjectsRowData: {}, //table每一行数据
  selectTableId: [], //选择表格数据
  roleIds: [],
  isSupplier: -1,
  isEditToubiao: false,
})

//项目管理模块功能按钮
const btnList = reactive([
  {
    name: '新增项目',
    icon: '',
    bgColor: '#25D390',
  },
  //   {
  //     name: '批量启用',
  //     icon: 'qiyong',
  //     bgColor: '#00A2FF',
  //   },
  //   {
  //     name: '批量禁用',
  //     icon: 'forbid',
  //     bgColor: '#FFB018',
  //   },
  //   {
  //     name: '批量删除',
  //     icon: 'shanchu',
  //     bgColor: '#F74B33',
  //   },
])

//区域加载
const loading = ref(true)
//右侧抽屉
const isShowProjectsDrawer = ref(false)
//项目成员设置
const isShowProjectsMember = ref(false)
onMounted(() => {
  getAllProjects()
  state.formModel.valid = state.formLabel[1].option[0].value
  let obj = JSON.parse(window.localStorage.getItem("userInfo"))
  state.roleIds = obj && obj.roleId
  console.log("state.roleIds",state.roleIds);
  state.isSupplier = state.roleIds.findIndex(item => 
    item == '058289cf3c57443b9225436ddde6e6a5'
 )
//供应商 058289cf3c57443b9225436ddde6e6a5
})

//获取所有的项目列表
const getAllProjects = () => {
  loading.value = true
  const params = {
    ipi: state.pagination.currentPage,
    ips: state.pagination.size,
    projectName: state.formModel.projectName,
    valid: state.formModel.valid,
  }
  getAllProjectsListAPI(params).then((res) => {
    const { status, data } = res
    if (status === 200) {
      loading.value = false
      state.tableData = data.result
      state.pagination.currentPage = data.pageNum
      state.pagination.size = data.pageSize
      state.pagination.total = data.total
      state.tableData.forEach((item) => {
        if (item.valid === null) {
          item.valid = false
        }
      })
    }
  })
}
//关闭项目抽屉
const ProjectsDrawerClose = () => {
  isShowProjectsDrawer.value = false
  state.ProjectsId = null
  state.id = ''
  state.ProjectsRowData = {}
  getAllProjects()
}
//删除项目
const deleteProjects = (id) => {
  delProjects({ id: id}).then((res) => {
    successHandle(res)
    getAllProjects()
  })
}
//批量启用
const batchStart = () => {
  batchStartRole(state.selectTableId).then((res) => {
    successHandle(res)
    getAllProjects()
  })
}
//批量禁用
const batchStop = () => {
  batchStopRole(state.selectTableId).then((res) => {
    successHandle(res)
    getAllProjects()
  })
}
//关闭项目成员设置
const ProjectsMemberClose = () => {
  isShowProjectsMember.value = false
}

//点击项目操作按钮
const clickHandle = (index) => {
  switch (index) {
    case 0: //新增项目
      state.ProjectsId = null
      state.id = ''
      isShowProjectsDrawer.value = true
      break
    case 1: //批量启用
      if (state.selectTableId.length > 0) {
        ElMessageBox.confirm(`您确定要批量启用？`, '操作提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          dangerouslyUseHTMLString: true,
          type: 'warning',
        })
          .then(async () => {
            batchStart()
          })
          .catch(() => { })
      } else {
        ElMessage({
          message: '至少选择一项',
          type: 'warning',
        })
      }
      break
    case 2: //批量禁用
      if (state.selectTableId.length > 0) {
        ElMessageBox.confirm(`您确定要批量禁用？`, '操作提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          dangerouslyUseHTMLString: true,
          type: 'warning',
        })
          .then(async () => {
            batchStop()
          })
          .catch(() => { })
      } else {
        ElMessage({
          message: '至少选择一项',
          type: 'warning',
        })
      }
      break
    case 3: //批量删除
      if (state.selectTableId.length > 0) {
        ElMessageBox.confirm(`您确定要批量删除？`, '操作提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          dangerouslyUseHTMLString: true,
          type: 'warning',
        })
          .then(async () => {
            //删除
            batchdelRole(state.selectTableId).then((res) => {
              successHandle(res);
              getAllProjects();
            });
          })
          .catch(() => { })
      } else {
        ElMessage({
          message: '至少选择一项',
          type: 'warning',
        })
      }
      break
  }
}

//表格筛选列---取消全选
const colSelect = (data, type, e, currentItem) => {
  if (type === 'filter') {
    const currentData = colFilters(data, e, currentItem, state.tableHeader)
    state.tableHeader = currentData
  } else {
    //全选/全取消
    state.tableHeader = data
  }
}

//表格中的操作
const tableEventCom = (type, data) => {
  switch (type) {
    case 'edit':
      isShowProjectsDrawer.value = true;
      state.ProjectsId = data.id;
      state.ProjectsRowData = data;
      break
    case 'detail':
      state.dialogVisible = true;
      state.ProjectsId = data.projectId;
      getDetail();
      break
    case 'del':
      ElMessageBox.confirm(`您确定要删除数据？`, '操作提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        dangerouslyUseHTMLString: true,
        type: 'warning',
      })
        .then(async () => {
          await deleteProjects(data.id)
        })
        .catch(() => { })
      break
    case 'enable':
      state.tableData.forEach((item) => {
        if (item.id === data.id) {
          item.valid = !item.valid
        }
      })
      ElMessageBox.confirm(`您确定要${!data.valid ? '启用' : '禁用'}？`, '操作提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        dangerouslyUseHTMLString: true,
        type: 'warning',
      })
        .then(async () => {
          let arr = []
          arr.push(data.id)
          state.selectTableId = arr
          !data.valid ? batchStart() : batchStop()
        })
        .catch(() => { })
      break
    case 'ProjectsMemberSetting':
      isShowProjectsMember.value = true
      state.ProjectsRowData = data
      break
    case 'toubiao' :
      isShowProjectsDrawer.value = true
      state.ProjectsId = data.projectId
      state.ProjectsRowData = data
      state.isEditToubiao = false
      break
    case 'edittoubiao' :
      isShowProjectsDrawer.value = true
      state.ProjectsId = data.projectId
      state.id = data.id
      state.isEditToubiao = true
      state.ProjectsRowData = data
      break
      
  }
}

const getDetail = () => {
  state.toubiaoDetailTable = []
  getToubiaoInfo({ projectId: state.ProjectsId }).then( res => {
    state.toubiaoDetailTable = res.data
  })
}

//搜索
const filter = () => {
  getAllProjects()
}
//重置
const reset = () => {
  for (let key in state.formModel) {
    state.formModel[key] = ''
  }
  getAllProjects()
}

//点击当前页
const getCurrentChange = (val) => {
  state.pagination.currentPage = val
  getAllProjects()
}

//点击条数
const getSizeChange = (val) => {
  state.pagination.size = val
  getAllProjects()
}

//选择表格数据
const getSelectChange = (row) => {
  state.selectTableId = row.map((item) => item.id)
}
</script>

<style lang="scss" scoped>
.Projects-management-container {
  .title {
    font-weight: 700;
    margin-bottom: 20px;
  }

  .main-left {
    width: 50%;
    background-color: $base-title-color;
    margin-right: 1%;
  }

  .main-right {
    width: 50%;
    background-color: $base-title-color;

    .ProjectsLimitsConfig {
      .tree {
        margin: 10px 0;
      }
    }
  }
}
</style>
